//
//  SQLitemanager.m
//  PiPiPineapple
//
//  Created by 李晓东 on 17/11/1.
//  Copyright © 2017年 PeanutXu. All rights reserved.
//
/**
    这里不使用 FMDataBase. 是因为--Using a single instance of FMDatabase from multiple threads at once is a bad idea. It has always been OK to make a FMDatabase object per thread. Just don't share a single instance across threads, and definitely not across multiple threads at the same time.
 */

#import "SQLitemanager.h"
#import "DoubleChromosphere_Extension.h"

#import <FMDB.h>

static NSString  *dbName = @"DoubleChromosphere.db";

@interface SQLiteManager() <SQLiteManagerQueryDelegate>

@property (nonatomic, strong) SQLiteManager *sqliteManager;
@property (nonatomic, strong) FMDatabaseQueue *db;
@property (nonatomic, strong) RetuenBlock returnBlock;

@end

@implementation SQLiteManager

+ (instancetype)share{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SQLiteManager alloc]initDataBase];
    });
    return instance;
}


- (instancetype)initDataBase{
    if (self = [super init]) {
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        path = [path stringByAppendingPathComponent:dbName];
        _db = [FMDatabaseQueue databaseQueueWithPath:path];
        NSLog(@"databasePath:%@", path);
        [self initTableView];
    }
    
    return self;
}
    
- (void)initTableView{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"db" ofType:@"sql"];
    NSString *sqlStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
    [_db inDatabase:^(FMDatabase * _Nonnull db) {
        [db executeStatements:sqlStr withResultBlock:^int(NSDictionary * _Nonnull resultsDictionary) {
            NSInteger count = [resultsDictionary[@"count"] integerValue];
            NSAssert(count == 1, @"顶,出错添");
            return 0;
        }];
        
    }];
    NSLog(@"fufuf");
}

- (void)insertDataOfArray:(NSArray *)array orDictionary:(NSDictionary *)dict inTable:(NSString *)tableName{
    
   [_db inDatabase:^(FMDatabase * _Nonnull db) {
       NSMutableString *mutableString = [NSMutableString string];
       NSMutableString *mutableValueString = [NSMutableString string];
       if (array == nil && dict != nil) {
           [mutableString appendFormat:@"insert into %@ (", tableName];
           [mutableValueString appendString:@" values ("];
           NSArray *keysArray = [dict allKeys];
           
           for (NSString *tempKey in keysArray) {
               [mutableString appendFormat:@"\'%@\', ", tempKey];
               [mutableValueString appendFormat:@"\'%@\', ", [dict valueForKey:tempKey]];
           }
           [mutableString replaceCharactersInRange:NSMakeRange(mutableString.length - 2, 1) withString:@")"];
           [mutableValueString replaceCharactersInRange:NSMakeRange(mutableValueString.length - 2, 1) withString:@")"];
           [mutableString appendString:mutableValueString];
       } else if(array != nil && dict == nil){
           for (DoubleChromosphere *obj in array) {
               [mutableString appendFormat:@"insert into %@ (redA, redB, redC, redD, redE, redF, blue, opencode, expect, opentime) values (", tableName];
               NSMutableString *valuesStr = [NSMutableString stringWithFormat:@"\"%@\", %@, %@, \"%@\"", [obj.returnBall componentsJoinedByString:@"\",\""], @"33", obj.returnIssueno, obj.returnOpendate];
               [mutableString appendFormat:@" %@); ", valuesStr];
               
           }
       }
       
       NSLog(@"这是 SQL 语句%@", mutableString);
       [db executeStatements:mutableString withResultBlock:^int(NSDictionary * _Nonnull resultsDictionary) {
           NSInteger count = [resultsDictionary[@"count"] integerValue];
           NSAssert(count == 1, @"顶,又出错");
           return 0;
       }];
   }];
}

- (void)queryDataBySQL:(NSString *)sql andReturnInHasBlock:(BOOL)flag andReturn:(RetuenBlock)returnBlock andNeedRefresh:(BOOL)needRefresh{
    
    [_db inDatabase:^(FMDatabase * _Nonnull db) {
        
        FMResultSet *resultSet = [db executeQuery:sql];
        NSMutableArray *mutableArray = [NSMutableArray array];
        while ([resultSet next]) {
            int columnCount = [resultSet columnCount];
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
            for (int i = 0; i < columnCount; i++) {
                
                NSString *key = [resultSet columnNameForIndex:i];
                NSString *value = [resultSet stringForColumn:key];
                
                dict[key] = value;
            }
            DoubleChromosphere *dcObj = [[DoubleChromosphere alloc]init];
            [dcObj setValues:dict];
            [mutableArray addObject:dcObj];
            
            
        }
        if (flag) {
            self.returnBlock = returnBlock;
            self.returnBlock(mutableArray, needRefresh);
        } else {
            [self.delegate loadDataFromSQLite3:mutableArray andIssueno:nil];

        }
    }];
}

- (void)queryDataInTable:(NSString *)tableName andOrderBy:(id)obj withParameter:(NSString *)key andValue:(NSString *)values, ...{

    NSMutableString *sql = [NSMutableString stringWithFormat:@"select * from %@ where 1 = 1 ", tableName];
    if (key != nil) {
        [sql appendFormat:@" and %@ = %@", key, values];
        va_list argList;
        va_start(argList, values);
        NSString *param = va_arg(argList, id);
        while (param) {
            [sql appendFormat:@" and %@ ", param];
            [sql appendString:@" = "];
            param = va_arg(argList, id);
            [sql appendFormat:@" %@ ", param];
            param = va_arg(argList, id);
        }
        va_end(argList);
        
    }

    [sql appendFormat:@" order by %@ desc limit 20;", obj];
    [self queryDataBySQL:sql andReturnInHasBlock:NO andReturn:nil andNeedRefresh:NO];

}

- (void)queryDataInTable:(NSString *)tableName andReturn:(RetuenBlock)returnBlock andOrderBy:(id)obj withParameter:(NSString *)key andValue:(NSString *)value ,...{
    
    NSMutableString *sql = [NSMutableString stringWithFormat:@"select * from %@ where 1 = 1 ", tableName];
    if (key != nil) {
        [sql appendFormat:@" and %@ = %@", key, value];
        va_list argList;
        va_start(argList, value);
        NSString *param = va_arg(argList, id);
        while (param) {
            [sql appendFormat:@" and %@ ", param];
            [sql appendString:@" = "];
            param = va_arg(argList, id);
            [sql appendFormat:@" %@ ", param];
            param = va_arg(argList, id);
        }
        va_end(argList);
        
    }
    
    [sql appendFormat:@" order by %@ desc limit 20;", obj];
    
    [self queryDataBySQL:sql andReturnInHasBlock:YES andReturn:returnBlock andNeedRefresh:NO];
}

- (void)queryDataInTable:(NSString *)tableName andOrderBy:(id)obj withParameter:(NSString *)key andValue:(NSString *)values andOperate:(NSString *)operate, ...{
    NSMutableString *sql = [NSMutableString stringWithFormat:@"select * from %@ where 1 = 1 ", tableName];
    if (key != nil) {
        [sql appendFormat:@" and %@ %@ %@", key, operate, values];
        va_list argList;
        va_start(argList, values);
        NSString *param = va_arg(argList, id);
        while (param) {
            [sql appendFormat:@" and %@ ", param];
            param = va_arg(argList, id);
            [sql appendFormat:@" %@ ", param];
            param = va_arg(argList, id);
            [sql appendFormat:@" %@ ", param];
            param = va_arg(argList, id);
        }
        va_end(argList);
        
    }
    [sql appendFormat:@" order by %@ desc  limit 10;", obj];
    
    [_db inDatabase:^(FMDatabase * _Nonnull db) {
        
        FMResultSet *resultSet = [db executeQuery:sql];
        NSMutableArray *mutableArray = [NSMutableArray array];
        while ([resultSet next]) {
            int columnCount = [resultSet columnCount];
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
            for (int i = 0; i < columnCount; i++) {
                
                NSString *key = [resultSet columnNameForIndex:i];
                NSString *value = [resultSet stringForColumn:key];
                
                dict[key] = value;
            }
            DoubleChromosphere *dcObj = [[DoubleChromosphere alloc]init];
            [dcObj setValues:dict];
            [mutableArray addObject:dcObj];
            
            
        }
        [self.delegate loadDataFromSQLite3:mutableArray andIssueno:values];
    }];
    
}

- (void)queryDataInTable:(NSString *)tableName andReturnBlock:(RetuenBlock)returnBlock andOrderBy:(id)obj andSort:(NSString *)sort andResultCount:(NSInteger)count withParameter:(NSString *)key andOperate:(NSString *)operate andValue:(NSString *)value ,...{
    NSMutableString *sql = [NSMutableString stringWithFormat:@" select * from %@ where 1 = 1 ", tableName];
    if (key) {
        [sql appendFormat:@" and %@ %@ %@ ", key, operate, value];
    }
    
    va_list argList;
    va_start(argList, value);
    NSString *keyStr = va_arg(argList, id);
    if (keyStr) {
        [sql appendFormat:@" and %@ ", keyStr];
        keyStr = va_arg(argList, id);
        [sql appendFormat:@" %@ ", keyStr];
        keyStr = va_arg(argList, id);
        [sql appendFormat:@" %@ ", keyStr];
        keyStr = va_arg(argList, id);
    }
    BOOL needRefresh = NO;
    if (key != nil) { // 为了判断是否是第一次加载
        needRefresh = YES;
    }
    
    [sql appendFormat:@" order by %@ %@", obj, sort];
    [sql appendFormat:@" limit %ld ", count];
    
    [self queryDataBySQL:sql andReturnInHasBlock:YES andReturn:returnBlock andNeedRefresh:needRefresh];
    
}
@end
